package org.springboot.demo.config;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class MyShiroConfig {
  //  配置 凭证匹配器  配置加密MD5
  @Bean
  public CredentialsMatcher credentialsMatcher(){
      HashedCredentialsMatcher credentialsMatcher =new HashedCredentialsMatcher();
      credentialsMatcher.setHashAlgorithmName("md5");
      credentialsMatcher.setHashIterations(1);
      return credentialsMatcher;
  }

    //自定义Realm  传入凭证匹配
  @Bean
  public Realm myRealms(CredentialsMatcher credentialsMatcher){
      MyRealms myRealm =new MyRealms();
    myRealm.setCredentialsMatcher(credentialsMatcher);
    return  myRealm;
  }


  //配置 DefaultWebSecurityManager 传入Myrealm
  @Bean
  public DefaultWebSecurityManager securityManager(Realm myRealm){
      DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
      securityManager.setRealm(myRealm);
      return securityManager;
  }

  //定义ShiroFiterFactoryBean 传入 secutiyManager
  @Bean
  public ShiroFilterFactoryBean  shiroFilterFactoryBean(SecurityManager securityManager){

    ShiroFilterFactoryBean  shiroFilterFactoryBean=new ShiroFilterFactoryBean();
    //写入secutityManager
    shiroFilterFactoryBean.setSecurityManager(securityManager);
    //成功跳转路径
    shiroFilterFactoryBean.setSuccessUrl("/shouye/shouye");
      //没有权限路径
    shiroFilterFactoryBean.setUnauthorizedUrl("403");
    // 错误路径
    shiroFilterFactoryBean.setLoginUrl("/login/main");
    //设置拦截页面
    Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
 //filterChainDefinitionMap.put("/login/login","anon/authc")
     filterChainDefinitionMap.put("/login/shouye","authc");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return  shiroFilterFactoryBean;

  }
}
